package P1线性结构.LeetCode双指针;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class LeetCode76 {
    TreeMap<Character, Integer> needMap = new TreeMap<>();
    TreeMap<Character, Integer> curMap = new TreeMap<>();

    public String minWindow(String s, String t) {
        //统计t中每个字符出现的次数
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            needMap.put(c, needMap.getOrDefault(c, 0) + 1);
        }
        int L = 0;
        int R = -1;
        int ansL = -1;
        int ansR = -1;
        int len = Integer.MAX_VALUE;
        while (R < s.length()) {
            R++;
            //向右扩张一个元素 判断元素的存在性
            if (R < s.length() && needMap.containsKey(s.charAt(R))) {
                char c = s.charAt(R);
                curMap.put(c, curMap.getOrDefault(c, 0) + 1);
                //既然都已经添加新元素 那就判断一下是否符合needMap的情况
                while (check() && L <= R) {    //区间至少保证有一个元素
                    if (R - L + 1 < len) {  //更新最小区间的
                        len = R - L + 1;
                        ansL = L;
                        ansR = R;
                    }
                    if (curMap.containsKey(s.charAt(L))) {
                        c = s.charAt(L);
                        curMap.put(c, curMap.getOrDefault(c, 0) - 1);
                    }
                    L++;
                }
            }
        }
        return ansL == -1 ? "" : s.substring(ansL, ansR + 1);
    }

    private boolean check() {
        Iterator it = needMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Character key = (Character) entry.getKey();
            Integer value = (Integer) entry.getValue();
            if (curMap.getOrDefault(key, 0) < value) {
                return false;
            }
        }
        return true;
    }
}
